package com.learn.queue.safety.blocking;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 消费者
 */
public class Consumer implements Runnable {

    private BlockingQueue<String> queue;
    //消费者编号
    private int consumerId;
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
    private static final int TIME_OUT = 2;

    //构造函数
    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    public Consumer(BlockingQueue<String> queue, int consumerId) {
        this.queue = queue;
        this.consumerId = consumerId;
    }

    public void run() {
        System.out.println("消费者-" + consumerId + "-启动消费线程！" + Thread.currentThread().getName());
        Random r = new Random();
        boolean isRunning = true;
        try {
            while (isRunning) {
                System.out.println("消费者-" + consumerId + "-正从队列获取数据...");
                String data = queue.poll(TIME_OUT, TimeUnit.SECONDS);

                //有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
                if (null != data) {
                    System.out.println("消费者-" + consumerId + "-拿到数据：" + data);
                    System.out.println("消费者-" + consumerId + "-正在消费数据：" + data);
                    Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP));
                } else {
                    // 超过2s还没数据，认为所有生产线程都已经退出，自动退出消费线程。
                    isRunning = false;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } finally {
            System.out.println("消费者-" + consumerId + "-退出消费者线程！"  + Thread.currentThread().getName());
        }
    }
}
